# ----------------------------------------------------------------------------
#       Copyright (C) 2013-2014 Huynh Vi Lam  <domovilam@gmail.com>
#
#       This file is part of pimucha.
#
#	This program is free software: you can redistribute it and/or modify
#	it under the terms of the GNU General Public License as published by
#	the Free Software Foundation, either version 3 of the License, or
#	(at your option) any later version.
#	
#	This program is distributed in the hope that it will be useful,
#	but WITHOUT ANY WARRANTY; without even the implied warranty of
#	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#	GNU General Public License for more details.
#	
#	You should have received a copy of the GNU General Public License
#	along with this program.  If not, see <http://www.gnu.org/licenses/>.
# ----------------------------------------------------------------------------

# ----------------------------------------------------------------------------
# Use to encode command
# ----------------------------------------------------------------------------
import logging,sys
logger = logging.getLogger()

from .cmdcontrollers import WITHControllers
CMDEncoders = {}

from .tsduolibs import *
CMDEncoders.update(TSDEncoders)

from .x10libs import *
CMDEncoders.update(X10Encoders)

try:
    from .rfxtrxlibs import *
    CMDEncoders.update(TRXEncoders)
except ImportError as e:
    print ("%s : %s" % (repr(e.__class__), str(e)))
    print ("Module RFXTRX not yet installed")


def cmdencode(params):
    """
    Encode an command for controller
    params = [protocol, houseunit, function, (level)]
    """
    logger.debug("Function cmdencode with parameters %s", repr(params))
    if len(params) == 3:
        params.append(None)
    protocol = params[0].upper()
    args = params[1:]
    if protocol in CMDEncoders:
        row = CMDEncoders[protocol]
    else:
        logger.debug('Unknown protocol for checking syntax %s',protocol)
        return None
    logger.debug("Function cmdencode %s", repr(row))
    try:
        a = eval(row[1])
        logger.debug("Encode value %s", repr(a))
    except Exception as e:
        logger.error("Exception / Error %s",repr(e))
        return None
    if a:
        cmd = row[0].lower() + a + row[2].lower()
    else:
        logger.error("Failed to encode %s with %s",repr(args),repr(row))
        return None
    if protocol in WITHControllers:
        ctrls =  WITHControllers[protocol]
        return [ctrls,protocol,cmd]
    else:
        logger.debug('Protocol %s associated with none controller',protocol)
        return [('NOCONTROLLER',),protocol,cmd]
 
